<!--
 * @author: 十一
 * @since: 2024-04-25
 * dictionary-components.vue
 * @desc: new page
-->
<template>
  <a-drawer
    v-model:open="open"
    width="1000"
    :title="title"
    @close="onClose"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="图标" v-bind="validateInfos.ico_url">
        <a-upload
          v-model:file-list="fileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :customRequest="uploadFile"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传图标</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="标题" v-bind="validateInfos.title">
        <a-input v-model:value="formState.title" />
      </a-form-item>
      <a-form-item label="分类">
        <a-select v-model:value="formState.category" placeholder="请选择所属分类">
          <a-select-option :value="item.id" v-for="item in categorys" :key="item.id">
            {{ item.title }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="描述" v-bind="validateInfos.description">
        <a-input v-model:value="formState.description" />
      </a-form-item>

      <a-form-item label="富文本" v-bind="validateInfos.rich_text">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
           
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="formState.rich_text"
            :defaultConfig="editorConfig"
            @onCreated="handleCreated"
          />
        </div>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
        <a-button @click="onSubmit" type="primary">提交</a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import { Form } from 'ant-design-vue'
import {DataEcho} from '@/utils/dataEcho'
import { addArticleBlog, editArticleBlog, uploadFiles, getClassificationList } from '@/servers/main'
import { message } from 'ant-design-vue'
import { useUserInfoStore } from '@/stores/userinfoStrore'
const { userInfo } = useUserInfoStore()

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 模拟 ajax 异步获取内容
// onMounted(() => {
//   setTimeout(() => {
//     formState.rich_text = ''
//   }, 1500)
// })

const toolbarConfig = {}
const editorConfig = { 
  placeholder: '请输入内容...' 
  
}
// editorConfig.MENU_CONF['uploadImage'] = {
//     // 其他配置...
//     server:"",
//     // 小于该值就插入 base64 格式（而不上传），默认为 0
//     base64LimitSize: 5 * 1024 // 5kb
// }

// 组件销毁时，也及时销毁编辑器
const editor = editorRef.value
console.log(Editor)
onBeforeUnmount(() => {
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
/**
 *
 * 富文本
 *
 * **/
// 上传

const fileList = ref([])
const loading = ref<boolean>(false)
const imageUrl = ref<string>('')

const uploadFile = (file: any) => {
  console.log(file)
  let formData = new FormData()
  formData.append('file', file.file)
  uploadFiles(formData).then((response: any) => {
    console.log(response)
    imageUrl.value = response.data
    formState.thumbnail = response.data
  })
}

const useForm = Form.useForm
const labelCol = { span: 2 }
const wrapperCol = { span: 22 }
const categorys = ref([])

function getData() {
  getClassificationList({}).then((response) => {
    categorys.value = response.results
  })
}
getData()
const formState = reactive({
  user_id: userInfo.id,
  category: '',
  thumbnail: '',
  title: '',
  description: '',
  rich_text: ''
})
const rules = reactive({
  ico_url: [{ required: true, message: '图标不能为空', trigger: 'change' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'change' }],
  resources_classify: [{ required: true, message: '分类不能为空', trigger: 'change' }]
})
const { resetFields, validate, validateInfos } = useForm(formState, rules)
const onSubmit = () => {
  validate()
    .then(() => {
      if (state.value == 0) {
        addArticleBlog(formState).then((res: any) => {
          if (res.status === 200) {
            message.success(res.message)
            emit('childGetData')
            onClose()
          } else {
            message.error(res.message)
          }
        })
      } else {
        editArticleBlog(formState).then((res: any) => {
          if (res.status === 200) {
            message.success(res.message)
            emit('childGetData')
            onClose()
          } else {
            message.error(res.message)
          }
        })
      }
    })
    .catch((err) => {
      console.log('error', err)
    })
}
const open = ref<boolean>(false)
const afterOpenChange = (bool: boolean) => {
  console.log('open', bool)
}
let title = ref<string>('')
let state = ref<number>(0)
const showDrawer = (value: any) => {
  open.value = true
  title.value = value.title
  state.value = value.state
  resetFields()
  if (value.state == 1) {
    DataEcho(formState, value.options)
    imageUrl.value = value.options.thumbnail
  }
}
const onClose = () => {
  resetFields()
  console.log(editor)
  title.value = '新增'
  open.value = false
  if (editor == null) return
  editor.destroy()
}
const emit = defineEmits(['childGetData'])
defineExpose({ showDrawer })
</script>
<style lang="less" scoped>
:deep .ant-row {
  align-items: center;
}
</style>
